const defaultSettings = require('../../config/defaultSettings')
import {request} from '../../utils/util';
import {initDict} from "../../api/dict"
Component({
  /**
   * 组件的属性列表
   */
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  properties: {
    pageSize:{
      type:Number,
      value:20
    },
    initQuery:{
      type:Array,
      value:[]
    },
    initOrder:{
      type:Array,
      value:[]
    },
    axiosUrl:{
      type:String,
      value:''
    },
    isAutoLoad:{//是否自动查询
      type:Boolean,
      value:true
    },
    dictCodes:String,
    dictCodeReplaceFields:{
      type:Array,
      value:[]
    },
    queryFormFields:{
      type:Array,
      value:[]
    },
    queryFormData:{
      type:Object,
      value:{}
    },
    queryFormId:{
      type:String,
      value:"queryForm"
    },
    formRules:{
      type:Object,
      value:{}
    },
    //页面数据ID前缀，必须要填写，因为根据这个进行判断数据是否显示
    pageIdPrefix:{
      type:String,
      value:'page'
    },
    //数据类型，根据这个来切换显示内容，因为微信小程序没有插槽作用域，所以暂时用此方法
    listType:{
      type:String,
      value:''
    },
    
    localDataSource:{
      type:Array,
      value:[]
    },
    meta:{
      type:Object,
      value:{}
    }
  },
  lifetimes: {
    created(){
      // console.log("***********")
    },
    ready(){
      let that = this
      wx.getSystemInfo({
        success: function (res) {
          that.setData({windowHeight: res.windowHeight});
        }
      });
      that.init()
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    list:[],//所有数据,原始数据
    groupHeightArr:[],//每一页的数据高度
    viewList:[],//渲染的数据
    windowHeight:0,
    triggered:false,//刷新状态，false 刷新未触发，true 表示刷新触发
    loading: false,//加载状态
    finished: false,//是否已经加载到最后一页
    primaryColor:defaultSettings.primaryColor,
    defaultSettings:defaultSettings,
    dataCenter:{
      pageNo:1,
      pageSize:20,
      orderColumns:[],
      queryForm:[],
    },
    /* 分组索引 */
    groupIndex:0,
    isShowCondition:false,
    localInitQuery:[],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    async init(){
      this.data.localInitQuery=this.data.initQuery
      if(this.data.dictCodes){
        await initDict(this.data.dictCodes)
      }
      
      //如果说直接传入本地数据，就不查询
      if(this.data.localDataSource.length>0){
        this.setPageData(1,this.data.localDataSource,this)
      }else if(this.data.isAutoLoad){
        this.searchQuery()
      }
    },
    getQueryParams(){
      let queryParamField=[]//临时存放QUERYFORM字段信息
      let queryFormVal = []
      let orderColumns=[]
      if(this.data.queryFormFields && this.data.queryFormFields.length>0){
        let queryForm = this.selectComponent('#list-'+this.data.queryFormId);
        if(queryForm){
          queryFormVal = queryForm.getQueryFormVal()
          for(let item of queryFormVal){
            queryParamField.push(item['field'])
          }
        }
      }
      if(this.data.localInitQuery && this.data.localInitQuery.length>0){
        for(let item of this.data.localInitQuery){
          if(queryParamField.length==0?true:!queryParamField.includes(item['field'])){
            queryFormVal.push(item)
          } 
        }
      }
      if(this.data.initOrder && this.data.initOrder.length>0){
        for(let item of this.data.initOrder){
          orderColumns.push(item)
        }
      }
      this.data.dataCenter.queryForm = queryFormVal
      this.data.dataCenter.orderColumns = orderColumns
      // console.log(this.data.dataCenter)
    },
    searchQuery(){
      if(this.data.localDataSource.length>0){
        //如果说有本地数据，这里就暂时不查询了
        this.setData({triggered:false,loading:false})
        return false
      }
      this.getQueryParams()
      this.data.dataCenter.pageNo=1
      this.data.groupIndex=0
      this.data.list=[]
      this.data.groupHeightArr=[]
      this.data.viewList=[]
      this.data.finished=false
      this.setData({triggered:true,isShowCondition:false})
      this.loadData()
    },
    loadDataMore(){
      let that = this
      if(that.data.finished){
        return
      }
      that.setData({loading:true})
      that.loadData()
    },
    loadData(){
      let that = this
      request({url:that.data.axiosUrl,data:that.data.dataCenter,}).then(res =>{
        let records = []
        if(res.result){
          records = res.result.records || res.result
          that.setPageData(res.result.pages,records,that)
          
          // console.log(that.data.list)
          // console.log(that.data.viewList)
        }
      }).finally(() => {
        that.setData({triggered:false,loading:false})
      })

    },
   
    setPageData(pages,records,that){
      if(that.data.dataCenter.pageNo==1){
        that.data.list=[]
        that.data.groupHeightArr=[]
        that.data.viewList=[]
      }
      //所有数据一页一页的放到集合中
      //把数据保存到 list 中,存放所有原始数据
      let newList = that.data.list
      newList[that.data.groupIndex] = records
      //页面加载的数据
      let newViewList = that.data.viewList
      newViewList[that.data.groupIndex]=records

      let newGroupIndex = that.data.groupIndex
      that.setData({viewList:newViewList,list:newList},()=>{that.setHeight(newGroupIndex)})
      if(that.data.dataCenter.pageNo<pages){
        that.data.dataCenter.pageNo = that.data.dataCenter.pageNo+1
        that.setData({finished:false,groupIndex:that.data.groupIndex+1})
      }else{
        that.setData({finished:true})
      }
    },
    setHeight(groupIndex) {
      const query = wx.createSelectorQuery().in(this);
      query && query
        .select(`#${this.data.pageIdPrefix+groupIndex}`)
        .boundingClientRect((res) => {
          /* 记录分组的高度 */
          this.data.groupHeightArr[groupIndex] = res && res.height;
          //如果数据放在子组件去显示，则此方法移到子组件中
          // this.observePage(groupIndex);
        }).exec();
    },
    observePage(groupIndex){
      wx.createIntersectionObserver(this)
        .relativeToViewport({
          /* 这里规定的有效区域为3个屏幕 ,缓存内容为3个屏幕大小*/
          top: 2 * this.data.windowHeight,
          bottom: 2 * this.data.windowHeight,
        })
        .observe(`#${this.data.pageIdPrefix+groupIndex}`, (res) => {
          const newViewList = this.data.viewList;
          const newList = this.data.list[groupIndex];
          if (res.intersectionRatio <= 0) {
            //隐藏
            /* 如果不在有效的视图范围内，那么不需要渲染真实的数据，只需要计算高度，进行占位就可以了。 */
            // console.log('当前分组：',groupIndex,'虚拟节点占位' )
            //计算出每一个ITEM的高度
            const listViewHeightArr = [];
            const listViewItemHeight = this.data.groupHeightArr[groupIndex] / newList.length
            for (let i = 0; i < newList.length; i++) {
              //将显示的数据替换成拥有一个listViewItemHeight 高度的元素，页面根据这个判断是否显示
              listViewHeightArr.push({ listViewItemHeight });
            }
            newViewList[groupIndex] = listViewHeightArr;
          }else{
            // console.log('当前分组：',groupIndex,'显示' )
            //显示
            newViewList[groupIndex]=this.data.list[groupIndex]
          }
          this.setData({viewList: newViewList,})
        })
    },
    addCondition(){
      this.setData({isShowCondition:true})
    },
    onClose(){
      this.setData({isShowCondition:false})
    },
    setInitQuery(initQuery){
      this.data.localInitQuery=initQuery
    }
    

  }
})
